/**
 * Copyright 2011 Joe Choi, All rights reserved.
 */
package tec.fs.syn;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import tao.data.structure.tree.TaoTree;
import tao.data.structure.tree.Traversal;
import tao.data.structure.tree.Traversal.Event;
import tec.fs.FileTree;

/**
 * @author Joe Choi
 */
public class FileSynchronizer {
	public FileSynchronizer(String srcPath, String repoPath) {
		srcTree = new FileTree(new File(srcPath));
		repoTree = new FileTree(new File(repoPath));
	}
	
	public void syn() {
		Traversal<File> preOrder = TaoTree.createTraversal(srcTree, Traversal.Order.Pre);
		preOrder.register(new Operator(repoTree));
		preOrder.start();
	}
	
	private FileTree srcTree, repoTree;
	
	private class Operator extends Traversal.Adaptor<File> {
		public Operator(FileTree repoTree) {
			this.destDir = repoTree.getValue();
		}
		
		@Override
		public void traversedTree(Event<File> event) {
			File srcFile = event.getTree().getValue();
			File destFile = new File(destDir, srcFile.getName());
			
			if(srcFile.isDirectory()) {
				if(! destFile.exists()) destFile.mkdir();
				destDir = destFile;
			} else if(srcFile.isFile()) {
				if((! destFile.exists()) || srcFile.lastModified() > destFile.lastModified()) 
					copyFile(srcFile, destFile);
			}
		}
		
		private File destDir;
	}
	
	private void copyFile(File src, File dest) {
		try {
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
			int b;
			
			while((b = in.read()) != -1) out.write(b);
			out.flush();
			
			in.close();
			out.close();
		} catch (IOException e) {
		}
	}
}
